package com.youthburin.base.util;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public class DwzUtils {
	private static List<DwzCondition> getDwzConditionList(HttpServletRequest request) {
		List<DwzCondition> conditions = new ArrayList<DwzCondition>();

		@SuppressWarnings("unchecked")
		Enumeration<String> paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String searchFieldName = paramNames.nextElement();
			if (StringUtils.startsWith(searchFieldName, DwzPagination.SEARCHFILEDNAME_PREFIX)) {
				String fieldName = searchFieldName.substring(searchFieldName
						.indexOf(DwzPagination.SEARCHFILEDNAME_PREFIX) + DwzPagination.SEARCHFILEDNAME_PREFIX.length());

				if (StringUtils.isNotBlank(fieldName)) {
					String op = request.getParameter(DwzPagination.SEARCHFIELDOPNAME_PREFIX + fieldName);
					String value = request.getParameter(searchFieldName);
					if (StringUtils.isNotBlank(value)) {
						DwzCondition condition = new DwzCondition();
						condition.setName(fieldName);
						if (StringUtils.isNotBlank(op)) {
							condition.setOp(DwzCondition.Operation.fromCode(op));
						} else {
							condition.setOp(DwzCondition.Operation.EQUALS);// 默认为等于
						}
						condition.setValue(value);
						conditions.add(condition);
					}
				}

			}
		}

		return conditions;
	}

	public static DwzPagination createDwzPagination(HttpServletRequest request) {
		DwzPagination dwzPagination = new DwzPagination();
		String pageNum = StringUtils.trimToEmpty(request.getParameter("pageNum"));
		String numPerPage = StringUtils.trimToEmpty(request.getParameter("numPerPage"));
		String orderField = StringUtils.trimToEmpty(request.getParameter("orderField"));
		String orderDirection = StringUtils.trimToEmpty(request.getParameter("orderDirection"));

		if (StringUtils.isNotEmpty(pageNum)) {
			dwzPagination.setPageNum(Integer.valueOf(pageNum));
		}
		if (StringUtils.isNotEmpty(numPerPage)) {
			dwzPagination.setNumPerPage(Integer.valueOf(numPerPage));
		}
		dwzPagination.setOrderField(orderField);
		dwzPagination.setOrderDirection(orderDirection);

		dwzPagination.setConditionList(getDwzConditionList(request));
		return dwzPagination;
	}
}
